package com.shawn.example.mvvmdemo

import android.app.Application
import android.util.Log
import com.alibaba.android.arouter.launcher.ARouter
import com.facebook.stetho.Stetho
import com.jetpack.mvvm.lib.base.bus.LiveDataBus
import com.jetpack.mvvm.lib.base.constants.Constants
import com.jetpack.mvvm.lib.base.interf.AppShareVMSupport
import com.jetpack.mvvm.lib.base.interf.ShareViewModelInterface
import com.jetpack.mvvm.lib.common.ModuleInit
import com.orhanobut.logger.AndroidLogAdapter
import com.orhanobut.logger.Logger
import com.tencent.mmkv.MMKV
import dagger.hilt.android.HiltAndroidApp
import kotlinx.coroutines.*
import javax.inject.Inject


@HiltAndroidApp
class DemoApp : Application(), AppShareVMSupport {
    companion object {
        private const val TAG = "DemoApp"
    }

    @Inject
    lateinit var shareVMDelegate: ShareViewModelInterface
    private var initJob: Job? = null
    private val scope: CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)

    override fun onCreate() {
        Log.e(TAG, "app onCreate")
        super.onCreate()
        Logger.addLogAdapter(AndroidLogAdapter())
        if (BuildConfig.DEBUG) {           // 这两行必须写在init之前，否则这些配置在init过程中将无效
            ARouter.openLog()     // 打印日志
            ARouter.openDebug()   // 开启调试模式(如果在InstantRun模式下运行，必须开启调试模式！线上版本需要关闭,否则有安全风险)
        }
        Log.e(TAG, "start init")
        initEnv()
        Log.e(TAG, "end init")
        if (BuildConfig.DEBUG) {
            Stetho.initializeWithDefaults(this)
        }
    }

    private fun initEnv() {
        val app = this
        initJob = scope.launch(Dispatchers.IO) {
            MMKV.initialize(app)
            ARouter.init(app)
            ModuleInit.initModules(app)
            LiveDataBus.get().with(Constants.LiveBusKeys.THIRD_SDK_INIT).postValue(Any())
        }
    }

    override fun getShareViewModelDel(): ShareViewModelInterface {
        return shareVMDelegate
    }

    override fun onTerminate() {
        super.onTerminate()
        ARouter.getInstance().destroy()
        initJob?.cancel()
    }
}